package com.mytime.feeds;

import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.mytime.database.Category;

public class CategoriesFeed {

	private static String request = "http://api.eventful.com/rest/categories/list?app_key=KJN78z24nttG7z2s";

	public static JSONObject getData() {
		JSONObject result = new JSONObject();
		JSONArray categories = new JSONArray();
		
		try {
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new URL(request).openStream());
			
			XPathFactory factory = XPathFactory.newInstance();
			XPath xPath = factory.newXPath();

			//Get all search Result nodes
			NodeList nodes = (NodeList) xPath.evaluate("/categories/category", doc, XPathConstants.NODESET);
			int nodeCount = nodes.getLength();

			//iterate over search Result nodes
			for (int i = 0; i < nodeCount; i++) {
				Node idNode = (Node) xPath.evaluate("id", nodes.item(i), XPathConstants.NODE);
				Node nameNode = (Node) xPath.evaluate("name", nodes.item(i), XPathConstants.NODE);
				
				Category c = new Category(idNode.getTextContent(), nameNode.getTextContent());
				categories.put(c.toJSON());
			}
			
			result.put("categories", categories);
			
		} catch (JSONException e) {
			e.printStackTrace();			
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
